package com.mondo.financialwallet.presentation.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.common.ui.AbsNetworkStateActivity;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.MyTokenListEntity;
import com.mondo.financialwallet.presentation.model.Token;
import com.mondo.financialwallet.presentation.ui.adapter.TokenListAdapter;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;


/**
 * 选择货币 activity
 */
public class TokenSelectActivity extends AbsNetworkStateActivity implements BaseQuickAdapter.OnItemClickListener {

    public static void launch(Activity context, int requestCode) {
        context.startActivityForResult(new Intent(context, TokenSelectActivity.class),
                requestCode);
    }

    @Bind(R.id.recycle_view_token_select) RecyclerView recycleViewTokenSelect;

    private TokenListAdapter mAdapter;

    @Override
    public int getTitleLayoutRes() {
        return R.layout.include_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_token_select;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_select_token);

        // 代币列表
        mAdapter = new TokenListAdapter(R.layout.recycle_view_token_select_item);
        mAdapter.setOnItemClickListener(this);
        recycleViewTokenSelect.setAdapter(mAdapter);

        // 请求我的代码列表
        requestMyTokenList();
    }

    private void requestMyTokenList() {
        loadingNetwork();

        DataRepository.get().myTokenList(result -> {
            successNetwork();
            if (result.isSuccess()) {
                mAdapter.setNewData(transformToken(result.getData()));
            }
        });
    }

    private List<Token> transformToken(List<MyTokenListEntity.DataBean> data) {
        List<Token> tokens = new ArrayList<>();
        for (MyTokenListEntity.DataBean datum : data) {
            tokens.add(new Token(
                    datum.getLogo(),
                            datum.getToken_id(),
                            datum.getFee(),
                            datum.getTitle_en(),
                    String.valueOf(datum.getUsd()),
                            String.valueOf(datum.getBalance())
                    )
            );
        }

        return tokens;
    }


    @Override
    public void onAnewRequest() {
        requestMyTokenList();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        finish(RESULT_OK, new Intent().putExtra("TOKEN", mAdapter.getItem(position)));
    }
}
